/******************************************************************************
 *	Author: 	Williams, Jacob (williamsj@msoe.edu)
 *	Class:		CE-3910
 *	Instructor:	Dr. Barnekow
 *****************************************************************************/
#include "uart.h"

/**
 * Initializes the UART with the following settings:
 * Baud Rate:               9600
 * Transmitter:             Enabled
 * Send Complete ISR:       Disabled
 * Receiver:                Enabled
 * Receive Complete ISR:    Disabled
 * Character Size:          8 bits
 * Stop Bits:               2
 * Parity:                  Odd
 */
void uartInit() {

    //Set baud rate
    UBRRH = (unsigned char) (UBBR_VALUE >> 8);
    UBRRL = (unsigned char) UBBR_VALUE;

    // Enable both the UART for transmitting and receiving
    UCSRB = (1 << RXEN) | (1 << TXEN);

    // Set the communication format
    // character size: 8
    // Stop bits: 2
    // Parity: odd
    UCSRC = (1 << URSEL) | (1 << USBS) | (3 << UCSZ0) | (3 << UPM0);
}

/**
 * Sends a character with the UART
 * @param data The character to be sent
 */
void uartPutc(char data) {

    // Wait until the UART is ready to send
    while (!(UCSRA & (1 << UDRE)))
        ;

    // Assign the data to the UART Data register to be sent
    UDR = data;

}

/**
 * Waits for a character to be received through the UART. NOTE: This function
 * is blocking and the system will hang until a character is received.
 * @return The character recieved on the UART
 */
char uartGetc(void) {

    // Wait until the UART is done receiving
    while (!(UCSRA & (1 << RXC)))
        ;

    // return the data in the UART Data Register
    return UDR;

}

